from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from client.models import UserAccount
from django.core.files.uploadedfile import TemporaryUploadedFile
from rest_framework.permissions import AllowAny, IsAuthenticated
from django.http import HttpResponse


# Create your views here.
class ResetPassword(APIView):
    permission_classes = [IsAuthenticated]

    def post(self, request):
        email = request.data["email"]
        password = request.data["password"]
        try:
            user = UserAccount.objects.get(email=email)
        except Exception as e:
            return Response({"error": str(e)}, status=status.HTTP_400_BAD_REQUEST)
        user.set_password(password)
        user.save()
        return Response({"success": "ok"}, status=status.HTTP_202_ACCEPTED)


class QueryPicture(APIView):
    permission_classes = [AllowAny]

    def get(self, request):
        id = request.GET.get("id", None)
        if id is None:
            return Response({"error": "not found"}, status=status.HTTP_400_BAD_REQUEST)
        avator = UserAccount.objects.get(id=id).avator
        if avator == b"":
            with open("test.png", "rb") as r:
                avator = r.read()
        return HttpResponse(
            avator,
            status=status.HTTP_200_OK,
            content_type="image/png",
        )


class UpdatePicture(APIView):
    permission_classes = [IsAuthenticated]

    def post(self, request):
        avator: TemporaryUploadedFile = request.FILES.get("avator", None)
        request.user.avator = avator.read()
        request.user.save()
        return Response(status=status.HTTP_204_NO_CONTENT)


class QueryProfile(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request):
        user = request.user
        return Response(
            {
                "id": user.id,
                "username": user.username,
                "email": user.email,
                "phone": user.phone,
            },
            status=status.HTTP_200_OK,
        )


class UpdateProfile(APIView):
    permission_classes = [IsAuthenticated]

    def post(self, request):
        data = request.data
        user = request.user
        for key, value in data.items():
            if key == "username":
                user.username = value
            elif key == "phone":
                user.phone = value
        user.save()
        return Response(status=status.HTTP_204_NO_CONTENT)
